﻿using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using Tools;

namespace SanFangWebApi.Filters
{
    public class ExceptionAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 统一对调用异常信息进行处理，返回自定义的异常信息
        /// </summary>
        /// <param name="context">HTTP上下文对象</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            //自定义异常的处理
            Exception ex = context.Exception;
            if (ex != null)
            {
                LogHelper.WriteErrorLog(ex.Message, ex);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {

                    //封装处理异常信息，返回指定JSON对象

                    Content = new StringContent("{\"Code\": \"9999\",\"Message\": \"接口出现了错误，请重试或者联系管理员\",\"Data\":Null}", System.Text.Encoding.UTF8, "application/json"),

                    ReasonPhrase = "exception"
                });
            }
        }
    }
}